# 断言工具封装
import json
import logging.handlers

import os

from config import DIR_PATH


def common_assert(response, status_code=None, expect_json=None, expect_text=None):
    # 如果Status_code不为空，那么就断言
    if status_code:
        assert response.status_code == status_code, "状态码断言错误，预期状态码:{}!=实际状态码:{}".format(status_code,
                                                                                        response.status_code)
    if expect_json:
        assert expect_json in response.json().get("json_description"), "实际结果:{}不包含，预期结果:{} ".format(response.json().get(
            "json_description"), expect_json
        )
    if expect_text:
        assert expect_text in response.text, "实际结果:{}不包含，预期结果:{}".format(response.text, expect_text)


# 读取json工具
def read_json(filename, key):
    filepath = DIR_PATH + "/data/" + filename
    with open(filepath, "r", encoding="utf-8") as f:
        arrs = []
        for data in json.load(f).get(key):
            arrs.append(tuple(data.values())[1:])
    return arrs


# 日志工具
class GetLog:
    @classmethod
    def get_log(cls):
        cls.log = None
        if cls.log is None:
            # 获取日志器
            cls.log = logging.getLogger()
            # 设置入口级别 INFO
            cls.log.setLevel(logging.INFO)
            filepath = DIR_PATH + os.sep + "log" + os.sep + "p2p.log"
            # 获取处理器TimedRotatingFileHandler:日志保存到文件且根据时间去分割
            tf = logging.handlers.TimedRotatingFileHandler(filename=filepath, when="midnight", interval=1,
                                                           backupCount=3, encoding="utf-8")
            # 获取格式器
            fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)]-%(message)s"
            fm = logging.Formatter(fmt)
            # 将格式器添加到文件中
            tf.setFormatter(fm)
            # 将文件添加到日志器中
            cls.log.addHandler(tf)
        # 返回日志器
        return cls.log


if __name__ == '__main__':
    #  print(read_json("register_login.json", "img_code"))
    GetLog.get_log().error("error级别测试")
    GetLog.get_log().info("信息级别测试")
    GetLog.get_log().warning("潜在危害级别测试")
    """
    核心思路：
           1，从json中读取数据
           2，再组装到列表元组中
    """
